package com.omronble.bp_broadcast;

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Button;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.google.gson.Gson;
import com.omronble.bp_broadcast.activity.UpdateActivity;
import com.omronble.bp_broadcast.bean.TLBean;
import com.omronble.bp_broadcast.bean.UpdateBean;
import com.omronble.bp_broadcast.tools.Constants;
import com.omronble.bp_broadcast.tools.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import okhttp3.Call;

public class UpdateService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        EventBus.getDefault().register(this);
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        EventBus.getDefault().unregister(this);
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(() -> Utils.getNetIp(UpdateService.this)).start();
        EventBus.getDefault().postSticky(new TLBean());
        getApkUpdate();
    }

    private void getApkUpdate() {
        OkHttpUtils.post()
                .url(Constants.UPDATE_APK).build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e( "UpdateService>>> " , e == null ? "onError" : e.getLocalizedMessage() );
//                        handler.postDelayed(() -> init(),500);
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Log.d( "UpdateService>>> " , response );
                        UpdateBean bean = new Gson().fromJson(response,UpdateBean.class);
                        if ( (bean.getClientVersionCode() <= Utils.getAppVersionCode(UpdateService.this)) ) {
                            //todo nothing
                        } else {  //can update
                            if ( !"must".equalsIgnoreCase(bean.getUpdateType()) ) {
                                AlertDialog.Builder builder = new AlertDialog
                                        .Builder(BpApplication.getInstance(),R.style.Theme_AppCompat_Light_Dialog);
                                builder.setTitle("提示");
                                builder.setMessage("有新的更新，是否现在更新！");
                                builder.setCancelable(false);
                                builder.setPositiveButton("是", (dialog, which) -> {
                                    startActivity(bean);
                                    dialog.dismiss();
                                });
                                builder.setNegativeButton("否", (dialogInterface, i) -> dialogInterface.dismiss());
                                AlertDialog alertDialog = builder.create();
                                alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                                alertDialog.show();
                                Button btnPos = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
                                Button btnNeg = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                                btnPos.setTextColor(Color.RED);
                                btnNeg.setTextColor(Color.RED);
                            } else {
                                startActivity(bean);
                            }
                        }
                    }
                });
    }

    private void startActivity (UpdateBean bean) {
        if ( isForeground(UpdateActivity.class.getName()) )
            return;
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setClass(this,UpdateActivity.class);
        intent.putExtra("UpdateBean",bean );
        startActivity(intent);
    }


    /**
     * 判断某个界面是否在前台,返回true，为显示,否则不是
     */
    public static boolean isForeground(String className) {
        if (TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) BpApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                cpn = list.get(0).topActivity;
                if ( null != cpn &&  className.equals(cpn.getClassName()))
                    return true;
            }
        }
        return false;
    }

}
